package com.ielts.activity;

import java.util.ArrayList;

import org.apache.http.Header;

import vn.com.baseapplication.BaseApplication;
import vn.com.baseapplication.activity.FBBaseLoginActivity;
import vn.com.baseapplication.common.view.ScrollViewDetectable;
import vn.com.baseapplication.common.view.ScrollViewDetectable.ScrollViewListener;
import vn.com.baseapplication.constant.BaseConstant;
import vn.com.baseapplication.util.Utils;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.text.Html;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.Window;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.facebook.FacebookException;
import com.facebook.Response;
import com.facebook.Session;
import com.facebook.SessionState;
import com.facebook.model.GraphUser;
import com.facebook.widget.FacebookDialog.PendingCall;
import com.ielts.IeltsConstant;
import com.ielts.model.ItemTopics;
import com.ielts.services.IeltsUrl;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.JsonHttpResponseHandler;

@SuppressLint("NewApi")
public class TopicActivity extends FBBaseLoginActivity implements
		ScrollViewListener, OnTouchListener {
	ItemTopics topic;
	TextView month, date;
	TextView content;
	ScrollViewDetectable topicScrollView;
	LinearLayout topicLayoutBtn;
	Animation UpToBottom, BottomToUp;
	TextView tvHeader;
	ImageView imvHeaderArrow;
	TextView topicHeaderTitle;
	Button btnBrainStorming, btnModeEssay, btnShare, btnBuy, btnBuy10, btnBuyYear;
	Handler mHandler = new Handler();

	@TargetApi(Build.VERSION_CODES.GINGERBREAD)
	protected void onCreate(android.os.Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_topic);
		tvHeader = (TextView) findViewById(R.id.header_tv_year);
		content = (TextView) findViewById(R.id.content);
		month = (TextView) findViewById(R.id.item_month);
		date = (TextView) findViewById(R.id.item_date);
		imvHeaderArrow = (ImageView) findViewById(R.id.header_iv_arrow);
		topicHeaderTitle = (TextView) findViewById(R.id.topic_header_title);
		topicScrollView = (ScrollViewDetectable) findViewById(R.id.topic_scrollview);
		topicLayoutBtn = (LinearLayout) findViewById(R.id.topic_layout_btn);
		btnBrainStorming = (Button) findViewById(R.id.btn_brainstorming);
		btnModeEssay = (Button) findViewById(R.id.btn_modelessay);
		btnShare = (Button) findViewById(R.id.btn_share);
		btnBuy = (Button) findViewById(R.id.btn_buy);
		btnBuy10 = (Button) findViewById(R.id.btn_buy_10_topic);
		btnBuyYear = (Button) findViewById(R.id.btn_buy_year_topic);

		btnBrainStorming.setPressed(true);
		
//		content.setBackgroundColor(0x00000000);
//		if (Build.VERSION.SDK_INT >= 11) content.setLayerType(WebView.LAYER_TYPE_SOFTWARE, null);
//
//		content.setWebViewClient(new WebViewClient()
//		{
//		    @Override
//		    public void onPageFinished(WebView view, String url)
//		    {
//		        view.setBackgroundColor(0x00000000);
//		        if (Build.VERSION.SDK_INT >= 11) view.setLayerType(WebView.LAYER_TYPE_SOFTWARE, null);
//		    }
//		});

		imvHeaderArrow.setVisibility(View.INVISIBLE);

		// topicScrollView.setOverScrollMode(ScrollView.OVER_SCROLL_ALWAYS);
		topicScrollView.setKeepScreenOn(true);
		topicScrollView.setScrollViewListener(this);
//		topicScrollView.setOnTouchListener(this);
		topic = (ItemTopics) getIntent().getSerializableExtra(
				BaseConstant.MSG_DATA);
		topic.refreshData();
		Log.e("TOPIC BUYED", topic.buyed + "");

		UpToBottom = (Animation) AnimationUtils.loadAnimation(this,
				R.anim.scroll_bottom_to_up);
		BottomToUp = (Animation) AnimationUtils.loadAnimation(this,
				R.anim.scroll_up_to_bottom);

		tvHeader.setText(IeltsApplication.getInstance().getValue(
				IeltsConstant.KEY_YEAR, IeltsConstant.KEY_YEAR_DEF));

//		content.setTextSize(TypedValue.COMPLEX_UNIT_SP, 20);
		// content.setLineSpace(15);
		// content.setAlignment(Align.LEFT);

//		content.setText(Html.fromHtml(topic.getFullSample()), TextView.BufferType.SPANNABLE);
		setTextContent(topic.getFullSample(),true);
		topicHeaderTitle.setText(topic.topic);
		String examDate = topic.examDate;
		String monthStr = Utils.getMonthStrFromNumber(Integer.parseInt(examDate.split("-")[1]));
		String dateStr = examDate.split("-")[2];
		month.setText(monthStr);
		date.setText(dateStr);

		mHandler.postDelayed(new Runnable() {
			
			@Override
			public void run() {
				btnBrainStorming.performClick();
				
				if(topic.topicType.equals("F")){
					btnModeEssay.performClick();
				}
			}
		}, 20);
	}

	@SuppressLint("SetJavaScriptEnabled")
	public void setTextContent(String text,boolean isHtml) {
//		content.getSettings().setJavaScriptEnabled(true);
//		content.loadData( "<html><body style='color:white;'>"+text+"<body></html>", "text/html", "UTF-8");
		
		content.setText(isHtml?Html.fromHtml(text):text, TextView.BufferType.SPANNABLE);
	}

	@Override
	public void onScrollChanged(ScrollViewDetectable scrollView, int x, int y,
			int oldx, int oldy) {
		// Log.e("delta", (y - oldy) + "");
		// boolean scrollUp = (y - oldy) > 0;

	};
	
	

	@Override
	public void onCompleted(GraphUser user, Response response) {
	}

	@Override
	public void onFailed(Session session, SessionState state,
			Exception exception) {
	}

	public void btnClicked(View v) {

		Button btn = (Button) v;

		switch (v.getId()) {
		case R.id.btn_share:
			if (!BaseApplication.haveInternet(this)) {
				BaseApplication.showNoConnectionDialog(this);
				return;
			}
			try {
				shareFb(getString(R.string.app_name),
						getString(R.string.fb_share_caption),
						IeltsUrl.URL_FANPAGE_WEB,
						IeltsUrl.URL_IELTS_ICON,
//						getString(R.string.fb_share_description),
						topic.topic+" - \n"+ topic.guide,
						new ArrayList<String>());
			} catch (FacebookException e) {
				e.printStackTrace();
				onShareFbComplete(null, e, null);
			}
			btnBuy.setVisibility(View.GONE);
			btnBuy10.setVisibility(View.GONE);
			break;
		case R.id.btn_brainstorming:
			resetBtn(btn, true);
			btn.setTextColor(Color.WHITE);
			btnBuy.setVisibility(View.GONE);
			btnBuy10.setVisibility(View.GONE);
			btnBuyYear.setVisibility(View.GONE);
//			content.setText(Html.fromHtml(topic.guide == null ? "" : topic.guide + ""), TextView.BufferType.SPANNABLE);
			setTextContent(topic.guide == null ? "" : topic.guide + "",false);
			topicLayoutBtn.startAnimation(BottomToUp);
			break;
		case R.id.btn_modelessay:
			resetBtn(btn, true);
			btn.setTextColor(Color.WHITE);
			btnShare.setVisibility(View.GONE);
//			content.setText(Html.fromHtml(topic.getFullSample()), TextView.BufferType.SPANNABLE);
			setTextContent(topic.getFullSample(),true);
			if (topic.buyed) {
				btnBuy.setVisibility(View.GONE);
				btnBuyYear.setVisibility(View.GONE);
			} else {
				btnBuy.setVisibility(View.VISIBLE);
				btnBuyYear.setVisibility(View.VISIBLE);
			}
			break;
		case R.id.btn_buy:
			if (!BaseApplication.haveInternet(this)) {
				BaseApplication.showNoConnectionDialog(this);
				return;
			}
			String urlBuyTopic = IeltsUrl.URL_BUY_TOPIC;
			String userId = IeltsApplication.getInstance().getValue(
					IeltsConstant.KEY_USER_ID, IeltsConstant.KEY_USER_ID_DEF);
			urlBuyTopic += "?custId=" + userId;
			urlBuyTopic += "&topicId=" + topic.id;
			network.get(IeltsConstant.GET_BUY_TOPIC, this, urlBuyTopic);

			break;
		case R.id.btn_buy_10_topic:
			if (!BaseApplication.haveInternet(this)) {
				BaseApplication.showNoConnectionDialog(this);
				return;
			}
			String urlBuy10Topic = IeltsUrl.URL_BUY_10_TOPIC;
			userId = IeltsApplication.getInstance().getValue(
					IeltsConstant.KEY_USER_ID, IeltsConstant.KEY_USER_ID_DEF);
			urlBuy10Topic += "custId=" + userId;
			urlBuy10Topic += "&topicId=" + topic.id;
			Log.e("BUY TOPIC 10", urlBuy10Topic);
			// network.get(IeltsConstant.GET_BUY_TOPIC_10, this, urlBuy10Topic);
			AsyncHttpClient client = new AsyncHttpClient();
			client.get(this, urlBuy10Topic, new JsonHttpResponseHandler() {
				@Override
				public void onFinish() {

				}

				@Override
				public void onSuccess(int statusCode, Header[] headers,
						String responseBody) {
					TopicActivity.this.onNetSuccess(
							IeltsConstant.GET_BUY_TOPIC_10, responseBody);
				}
			});
			break;
		case R.id.btn_buy_year_topic:
			if (!BaseApplication.haveInternet(this)) {
				BaseApplication.showNoConnectionDialog(this);
				return;
			}
			String urlBuyYearTopic = IeltsUrl.URL_BUY_YEAR_TOPIC;
			userId = IeltsApplication.getInstance().getValue(
					IeltsConstant.KEY_USER_ID, IeltsConstant.KEY_USER_ID_DEF);
			String year = IeltsApplication.getInstance().getValue(
					IeltsConstant.KEY_YEAR, IeltsConstant.KEY_YEAR_DEF);
			urlBuyYearTopic += "?custId=" + userId;
			urlBuyYearTopic += "&year=" + year;
			Log.e("BUY TOPIC YEAR", urlBuyYearTopic);
			// network.get(IeltsConstant.GET_BUY_TOPIC_10, this, urlBuy10Topic);
			client = new AsyncHttpClient();
			client.get(this, urlBuyYearTopic, new JsonHttpResponseHandler() {
				@Override
				public void onFinish() {

				}

				@Override
				public void onSuccess(int statusCode, Header[] headers,
						String responseBody) {
					TopicActivity.this.onNetSuccess(
							IeltsConstant.GET_BUY_TOPIC_YEAR, responseBody);
				}
			});
			break;
		default:
			break;
		}

	}

	@Override
	public void onNetSuccess(int requestId, final String response) {
		switch (requestId) {
		case IeltsConstant.GET_BUY_TOPIC:
			Log.e("BUY TOPIC", response);
			if (response.contains("\"dataValue\":\"1\"")) {
				mHandler.post(new Runnable() {

					@Override
					public void run() {
						Toast.makeText(TopicActivity.this, "Buy Topic Success!",
								Toast.LENGTH_SHORT).show();
						topic.buyed = true;
//						content.setText(Html.fromHtml(topic.getFullSample()), TextView.BufferType.SPANNABLE);
						setTextContent(topic.getFullSample(),true);
						btnBuy.setVisibility(View.GONE);
						btnBuyYear.setVisibility(View.GONE);
					}
				});
			} else {
				mHandler.post(new Runnable() {

					@Override
					public void run() {
						Toast.makeText(TopicActivity.this, "Buy Topic Failed!",
								Toast.LENGTH_SHORT).show();
					}
				});
			}
			break;
		case IeltsConstant.GET_BUY_TOPIC_10:
			Log.e("BUY TOPIC 10", response);
			if (response.contains("<dataValue>1</dataValue>")) {
				mHandler.post(new Runnable() {

					@Override
					public void run() {
						Toast.makeText(TopicActivity.this, "Buy Topic Success!",
								Toast.LENGTH_SHORT).show();
						topic.buyed = true;
//						content.setText(Html.fromHtml(topic.getFullSample()), TextView.BufferType.SPANNABLE);
						setTextContent(topic.getFullSample(),true);
					}
				});
			} else {
				mHandler.post(new Runnable() {

					@Override
					public void run() {
						Toast.makeText(TopicActivity.this, "Buy Topic Failed!",
								Toast.LENGTH_SHORT).show();
					}
				});
			}
			break;
		case IeltsConstant.GET_BUY_TOPIC_YEAR:
			Log.e("BUY TOPIC YEAR", response);
			if (response.contains("{\"dataValue\":\"1\"}")) {
				mHandler.post(new Runnable() {

					@Override
					public void run() {
						Toast.makeText(TopicActivity.this, "Buy Topic Success!",
								Toast.LENGTH_SHORT).show();
						topic.buyed = true;
//						content.setText(Html.fromHtml(topic.getFullSample()), TextView.BufferType.SPANNABLE);
						setTextContent(topic.getFullSample(),true);
					}
				});
			} else {
				mHandler.post(new Runnable() {

					@Override
					public void run() {
						Toast.makeText(TopicActivity.this, "Buy Topic Failed!",
								Toast.LENGTH_SHORT).show();
					}
				});
			}
			break;
		default:
			break;
		}
	}

	@Override
	public void onShareFbComplete(PendingCall pendingCall, Exception error,
			Bundle data) {
		if (error != null) {
			Toast.makeText(this, getString(R.string.fb_share_notice_failed),
					Toast.LENGTH_SHORT).show();
			return;
		}
		
//		 Toast.makeText(this, getString(R.string.fb_share_notice_success), Toast.LENGTH_SHORT).show();
	}

	public void resetBtn() {
		resetBtn(null, false);
	}

	public void resetBtn(Button btn, boolean pressed) {

		btnShare.setVisibility(View.VISIBLE);
		btnBuy.setVisibility(View.VISIBLE);
		// btnBuy10.setVisibility(View.VISIBLE);
		btnBuyYear.setVisibility(View.VISIBLE);

		btnBrainStorming.setBackgroundResource(R.drawable.btn_topic_default);
		btnModeEssay.setBackgroundResource(R.drawable.btn_topic_default);
		btnBrainStorming.setTextColor(Color.WHITE);
		btnModeEssay.setTextColor(Color.WHITE);

		if (btn != null) {
			if (pressed) {
				btn.setBackgroundResource(R.drawable.btn_topic_selected);
			} else {
				btn.setBackgroundResource(R.drawable.btn_topic_default);
			}
		}
	}

	float startY;
	boolean isDown;
	boolean isLastDown = false;
	boolean flag = true;
	boolean flag2 = false;

	@Override
	public boolean onTouch(View v, MotionEvent event) {
		if (topic != null && !topic.buyed)
			return false;
		if ((content.getText()+"").toString().length() < 50)
			return false;
		switch (event.getAction()) {
		case MotionEvent.ACTION_DOWN:
			startY = event.getY();
			break;
		case MotionEvent.ACTION_MOVE:
			float crtY = event.getY();
			isDown = crtY > startY;
			break;
		case MotionEvent.ACTION_UP:
			BottomToUp.cancel();
			BottomToUp.reset();
			UpToBottom.cancel();
			UpToBottom.reset();
			if (isDown) {
				// scroll down
				if (flag2) {
					topicLayoutBtn.startAnimation(BottomToUp);
					flag2 = false;
				}
				flag = true;
			} else {
				// scroll up
				if (flag) {
					topicLayoutBtn.startAnimation(UpToBottom);
					flag = false;
				}
				flag2 = true;
			}
			break;

		default:
			break;
		}
		return false;
	}
}
